package code.nest.partitioner;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.record.InvalidRecordException;
import org.apache.kafka.common.utils.Utils;

import java.util.List;
import java.util.Map;

/**
 * @author ：Hyman
 * @date ：Created in 2021/6/29 19:04
 * @description：
 * @modified By：
 * @version: $
 */
public class MyPartitioner implements Partitioner {
    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topic);
        int num = partitionInfos.size();
        if ((keyBytes == null) || (!(key instanceof String))) {
            throw new InvalidRecordException("未设置键值或者键值设置错误。");
        }
        //Banana总是分配到最后一个分区
        if (("error").equals((String) key) ||
                num < 2) {
            System.out.println("error 消息放到最后分区。" + (num - 1));
            return num - 1;
        }
        return (Math.abs(Utils.murmur2(keyBytes)) % (num - 1));
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> map) {

    }
}
